package com.lsp.server.common.interceptor;

import com.lsp.server.user.domain.po.Org;
import com.lsp.server.user.service.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @ClassName CrossInterceptor
 * @Description 跨域拦截器
 * @Author Mr Hao
 * @Date 2021/11/15 17:29
 */
@Component
public class CrossInterceptor implements HandlerInterceptor {

    @Autowired
    private OrgService orgService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求ip
        String ipAddr = request.getRemoteAddr();
        //获取请求域
       // String origin = request.getHeader("Origin");
        String origin = request.getHeader("Origin");
        //查询所有允许跨域的域名
        List<Org> orgs = orgService.queryList();
                        //(List<Org>) redisTemplate.opsForValue().get("orgData_elect")
        //判断是否是白名单
        boolean flag = false;
        for (int i = 0; i <orgs.size() ; i++) {
            if (ipAddr.equals(orgs.get(i).getName())){
                flag = true;
                break;
            }
        }
        //判断是否是白名单
        if (flag == true){
            response.setHeader("Access-Control-Allow-Origin",origin);
        }else {//不在白名单内
            //响应错误信息
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = null;
            try{
                writer = response.getWriter();
            }catch (IOException e){
                e.printStackTrace();
            }
            writer.write("{\"code\":3000,\"msg\":\""+ipAddr+" 不在白名单内  如需要 请联系 席先生  电话为 13938433630  欢迎致电，\"}");
        }
        return flag;
    }
}